package com.zhongen.oa.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhongen.admin.api.entity.SysFile;
import com.zhongen.common.core.util.PinyinUtils;
import com.zhongen.common.core.util.R;
import com.zhongen.oa.entity.*;
import com.zhongen.oa.mapper.AskForLeaveMapper;
import com.zhongen.oa.mapper.ProjectBasicInfoMapper;
import com.zhongen.oa.mapper.ProjectContractMapper;
import com.zhongen.oa.mapper.ProjectPreReportApplyMapper;
import com.zhongen.oa.service.InstanceProgressService;
import com.zhongen.oa.service.ProcessFinishedHandlerService;
import com.zhongen.oa.service.ProjectFileService;
import com.zhongen.wflow.workflow.bean.process.form.Form;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Service
public class ProcessFinishedHandlerServiceImpl implements ProcessFinishedHandlerService {

	@Autowired
	InstanceProgressService instanceProgressService;

	@Autowired
	ProjectPreReportApplyMapper preReportApplyMapper;

	@Autowired
	ProjectBasicInfoMapper projectBasicInfoMapper;

	@Autowired
	ProjectContractMapper projectContractMapper;

	@Autowired
	AskForLeaveMapper askForLeaveMapper;

	private final ProjectFileService projectFileService;

	@Override
	public boolean saveProjectInfo(JSONObject param) {
		JSONObject progressInfo = instanceProgressService.getInstanceProgressInfo(param);
		// 入库
		ProjectBasicInfoEntity projectBasicInfo = new ProjectBasicInfoEntity();

		Map<String, Object> formDatas = (Map<String, Object>) progressInfo.get("formDatas");
		List<Form> formItems = progressInfo.getJSONArray("formItems").toJavaList(Form.class);
		for (Form item : formItems) {
			switch (item.getTitle()) {
				case "项目名称":
					projectBasicInfo.setProjectName(formDatas.get(item.getId()).toString());
					break;
				case "项目类型":
					String type = formDatas.get(item.getId()).toString();
					projectBasicInfo.setProjectType(type.substring(1, type.length() - 1));
					break;
				case "项目缩写":
					projectBasicInfo.setProjectAbbr(formDatas.get(item.getId()).toString());
					break;
				case "省市":
					String city = formDatas.get(item.getId()).toString();
					String[] split = city.split("-");
					projectBasicInfo.setProvince(split[0]);
					projectBasicInfo.setArea(split[1]);
					break;
				case "项目内容":
					projectBasicInfo.setProjectContent(formDatas.get(item.getId()).toString());
					break;
				default:
					break;
			}
		}
		// 先默认的
		projectBasicInfo.setDeptId(1L);

		// 查询顺序号
		Long count = projectBasicInfoMapper
			.selectCount(new QueryWrapper<ProjectBasicInfoEntity>().eq("project_approval_status", "approval")
				.eq("DATE_FORMAT (project_approval_date,'%Y-%m')",
						LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy-MM")));
		// 生成项目编号
		String area = projectBasicInfo.getArea();
		if (null == area || "".equals(area)) {
			area = projectBasicInfo.getProvince();
		}
		String areaName = "";
		if (null != area && !"".equals(area)) {
			area = projectBasicInfo.getProvince();
			areaName = "-" + PinyinUtils.getPinyinFirstLetter(area);
		}
		String projectType = projectBasicInfo.getProjectType();
		projectBasicInfo.setProjectApprovalDate(LocalDate.now());
		String yearAndMonth = "-" + LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyMM");
		String no = formatNumberToThreeDigits(count + 1);
		String projectCode = projectType + areaName + yearAndMonth + no;
		projectBasicInfo.setProjectNumber(projectCode);
		projectBasicInfo.setCreateTime(LocalDate.now().atStartOfDay());
		projectBasicInfo.setInstanceId(param.getString("instanceId"));
		projectBasicInfo.setProjectApprovalStatus("approval");

		return projectBasicInfoMapper.insert(projectBasicInfo) > 0;
	}

	@Override
	public boolean saveProjectContract(JSONObject param) {
		JSONObject projectContract = instanceProgressService.getInstanceProgressInfo(param);

		// 入库
		ProjectContractEntity projectContractEntity = new ProjectContractEntity();

		Map<String, Object> formDatas = (Map<String, Object>) projectContract.get("formDatas");
		List<Form> formItems = projectContract.getJSONArray("formItems").toJavaList(Form.class);
		for (Form item : formItems) {
			switch (item.getTitle()) {
				case "合同名称":
					projectContractEntity.setContractName(formDatas.get(item.getId()).toString());
					break;
				case "合同内容":
					projectContractEntity.setContractContent(formDatas.get(item.getId()).toString());
					break;
				case "合同金额":
					projectContractEntity.setContractMoney(new BigDecimal(formDatas.get(item.getId()).toString()));
					break;
				case "合同类型":
					String type = formDatas.get(item.getId()).toString();
					projectContractEntity.setContractType(type.substring(1, type.length() - 1));
					break;
				case "选择项目":
					String project = formDatas.get(item.getId()).toString();
					String id = project.substring(project.indexOf("id=") + 3);
					id = id.substring(0, id.indexOf(","));
					ProjectBasicInfoEntity projectBasicInfo = projectBasicInfoMapper.getProjectNumberByInstanceId(id);
					projectContractEntity.setProjectNumber(projectBasicInfo.getProjectNumber());
					projectContractEntity.setProjectId(projectBasicInfo.getId());
					break;
				default:
					break;
			}
		}
		projectContractEntity.setSignDate(LocalDate.now());
		projectContractEntity.setCreateTime(LocalDate.now().atStartOfDay());

		// 根据项目编号查询合同序号
		ProjectContractEntity result = projectContractMapper.selectOne(Wrappers.<ProjectContractEntity>query()
			.eq("project_number", projectContractEntity.getProjectNumber())
			.select("IFNULL(MAX(contract_sort),0) as contract_sort"));
		projectContractEntity.setContractNumber(projectContractEntity.getProjectNumber() + "-"
				+ projectContractEntity.getSignDate().format(DateTimeFormatter.ofPattern("yyMM")) + "-"
				+ formatNumberToThreeDigits(result.getContractSort() + 1));
		return projectContractMapper.insert(projectContractEntity) > 0;
	}

	@Override
	public boolean addAskLeaveApply(JSONObject param) {
		JSONObject progressInfo = instanceProgressService.getInstanceProgressInfo(param);
		// 入库
		Long createId = progressInfo.getLong("createId");
		AskForLeaveEntity entity = new AskForLeaveEntity();
		if (createId != null) {
			entity.setUserId(createId);
		}
		entity.setInstanceId(param.getString("instanceId"));
		Map<String, Object> formDatas = (Map<String, Object>) progressInfo.get("formDatas");
		List<Form> formItems = progressInfo.getJSONArray("formItems").toJavaList(Form.class);
		for (Form item : formItems) {
			switch (item.getTitle()) {
				case "请假类型":
					entity.setLeaveType(formDatas.get(item.getId()).toString());
					break;
				case "请假时间":
					List array = (List) formDatas.get(item.getId());
					entity.setStartDate(
							LocalDate.parse(array.get(0).toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
					entity.setEndDate(
							LocalDate.parse(array.get(1).toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
					break;
				case "天数":
					entity.setDays((Double) formDatas.get(item.getId()));
					break;
				case "请假理由":
					entity.setReason(formDatas.get(item.getId()).toString());
					break;
			}
		}
		return askForLeaveMapper.insert(entity) > 0;
	}

	@Override
	public R addProjectReportApply(JSONObject param) {
		JSONObject progressInfo = instanceProgressService.getInstanceProgressInfo(param);
		// 入库
		ProjectBasicInfoEntity projectBasicInfo = new ProjectBasicInfoEntity();
		projectBasicInfo.setInstanceId(param.getString("instanceId"));
		Map<String, Object> formDatas = (Map<String, Object>) progressInfo.get("formDatas");
		List<Form> formItems = progressInfo.getJSONArray("formItems").toJavaList(Form.class);
		for (Form item : formItems) {
			switch (item.getTitle()) {
				case "项目名称":
					projectBasicInfo.setProjectName(formDatas.get(item.getId()).toString());
					break;
				case "项目内容":
					projectBasicInfo.setProjectContent(formDatas.get(item.getId()).toString());
					break;
				case "项目所属地区":
					projectBasicInfo.setProjectAbbr(formDatas.get(item.getId()).toString());
					break;
				case "备注":
					projectBasicInfo.setRemark(formDatas.get(item.getId()).toString());
					break;
			}
		}

		// 项目名称字母大写
		projectBasicInfo.setProjectAbbr(projectBasicInfo.getProjectAbbr().toUpperCase());
		// 校验项目缩写是否存在
		Long exist = projectBasicInfoMapper.selectCount(
				new QueryWrapper<ProjectBasicInfoEntity>().eq("project_abbr", projectBasicInfo.getProjectAbbr()));
		if (exist > 0) {
			return R.failed("项目缩写已存在");
		}

		projectBasicInfo.setDeptId(param.getLong("owner.deptId"));

		// 项目初始状态
		projectBasicInfo.setProjectStatus("ready");
		// 项目状态.判断立项日期是否小于当前日期,小于则是已立项,立项之后再生成项目编号
		projectBasicInfo.setProjectApprovalStatus("disapproval");
		if (null != projectBasicInfo.getProjectApprovalDate()) {
			// 项目年份根据立项日期自动生成
			projectBasicInfo
				.setProjectYear(LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy"));
			if (projectBasicInfo.getProjectApprovalDate().compareTo(LocalDate.now()) <= 0) {
				projectBasicInfo.setProjectApprovalStatus("approval");
				// 查询顺序号
				Long count = projectBasicInfoMapper
					.selectCount(new QueryWrapper<ProjectBasicInfoEntity>().eq("project_approval_status", "approval")
						.eq("DATE_FORMAT (project_approval_date,'%Y-%m')",
								LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy-MM")));
				// 生成项目编号
				String area = projectBasicInfo.getArea();
				if (null == area || "".equals(area)) {
					area = projectBasicInfo.getProvince();
				}
				String areaName = "";
				if (null != area && !"".equals(area)) {
					area = projectBasicInfo.getProvince();
					areaName = "-" + PinyinUtils.getPinyinFirstLetter(area);
				}
				String projectType = projectBasicInfo.getProjectType();
				String yearAndMonth = "-" + LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyMM");
				String no = formatNumberToThreeDigits(count + 1);
				String projectCode = projectType + areaName + yearAndMonth + no;
				projectBasicInfo.setProjectNumber(projectCode);
			}
		}
		projectBasicInfoMapper.insert(projectBasicInfo);
		// 插入附件
		ArrayList<ProjectFileEntity> projectFileEntities = new ArrayList<>();
		List<SysFile> fileList = projectBasicInfo.getFileList();
		if (null != fileList && fileList.size() > 0) {
			for (SysFile file : fileList) {
				ProjectFileEntity projectFileEntity = new ProjectFileEntity();
				projectFileEntity.setProjectId(projectBasicInfo.getId());
				projectFileEntity.setFileId(Long.valueOf(file.getId()));
				projectFileEntities.add(projectFileEntity);
			}
			projectFileService.saveBatch(projectFileEntities);
		}
		return R.ok();
	}

	private String formatNumberToThreeDigits(long number) {
		String numberString = String.valueOf(number);
		if (numberString.length() < 3) {
			numberString = String.format("%02d", number);
		}
		return numberString;
	}

}
